package center

import (
	"barge/app"
	"barge/pkg/uix"
	"github.com/pkg/errors"
	"github.com/rs/zerolog/log"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
	"strconv"
)

// setCmd represents the base command when called without any subcommands
var setCmd = &cobra.Command{
	Use:   "set",
	Short: "设置中转服务器信息",
	Long:  ``,
	Args: func(cmd *cobra.Command, args []string) error {
		if center.Name == "" && len(args) > 0 {
			center.Name = args[0]
		}

		if viper.GetBool("interactive") {
			if center.Name == "" {
				center.Name = uix.Input("请输入中转服务器名称：")
			}
			if center.Name == "localhost" {
				return errors.New("中转服务器名称不能设置为保留的 localhost")
			}
			if center.Host == "" {
				center.Host = uix.Input("请输入中转服务器地址：")
			}
			if center.Port == 0 {
				port := uix.Input("请输入中转服务器端口：")
				pi, err := strconv.Atoi(port)
				if err != nil {
					return err
				}
				center.Port = pi
			}
			if center.Username == "" {
				center.Username = uix.Input("请输入中转服务器用户：")
			}
			if center.Password.Raw == "" {
				center.Password.Raw = uix.Input("请输入中转服务器密码：")
			}
		}

		if center.Name == "" {
			return errors.New("中转服务器名称不能为空")
		}
		if center.Name == "localhost" {
			return errors.New("中转服务器名称不能设置为保留的 localhost")
		}
		if center.Host == "" {
			return errors.New("中转服务器地址不能为空")
		}
		if center.Port == 0 {
			return errors.New("中转服务器端口不能为空")
		}
		return nil
	},
	Run: func(cmd *cobra.Command, args []string) {
		m, err := app.NewConfigManager(viper.GetString("configPath"))
		if err != nil {
			log.Err(err).Str("path", viper.GetString("configPath")).Send()
			return
		}
		m.SetCenter(center)
		err = m.Save()
		if err != nil {
			log.Err(err).Str("path", viper.GetString("configPath")).Send()
			return
		}
	},
}

var center = new(app.CenterOption)

func init() {
	centerCmd.AddCommand(setCmd)
	setCmd.Flags().StringVarP(&center.Name, "name", "n", "", "中转服务器名称")
	setCmd.Flags().StringVarP(&center.Host, "host", "H", "", "中转服务器地址")
	setCmd.Flags().IntVarP(&center.Port, "port", "P", 22, "中转服务器端口")
	setCmd.Flags().StringVarP(&center.Username, "username", "u", "root", "中转服务器用户")
	setCmd.Flags().StringVarP(&center.Password.Raw, "password", "p", "", "中转服务器密码")
}
